// store/hooks.js
// 状态管理工具函数

const appStore = require('./index')

/**
 * 页面状态管理混入
 * 为页面提供状态管理能力
 */
function createPageWithStore(pageConfig) {
  const originalOnLoad = pageConfig.onLoad
  const originalOnUnload = pageConfig.onUnload
  
  let unsubscribe = null
  
  return {
    ...pageConfig,
    data: {
      ...pageConfig.data,
      store: appStore.getState()
    },
    
    onLoad(options) {
      // 订阅状态变化
      unsubscribe = appStore.subscribe((state) => {
        this.setData({
          store: state
        })
      })
      
      // 调用原始的 onLoad
      if (originalOnLoad) {
        originalOnLoad.call(this, options)
      }
    },
    
    onUnload() {
      // 取消订阅
      if (unsubscribe) {
        unsubscribe()
        unsubscribe = null
      }
      
      // 调用原始的 onUnload
      if (originalOnUnload) {
        originalOnUnload.call(this)
      }
    },
    
    // 添加状态管理方法
    $store: appStore
  }
}

/**
 * 组件状态管理混入
 * 为组件提供状态管理能力
 */
function createComponentWithStore(componentConfig) {
  const originalAttached = componentConfig.attached
  const originalDetached = componentConfig.detached
  
  let unsubscribe = null
  
  return {
    ...componentConfig,
    data: {
      ...componentConfig.data,
      store: appStore.getState()
    },
    
    attached() {
      // 订阅状态变化
      unsubscribe = appStore.subscribe((state) => {
        this.setData({
          store: state
        })
      })
      
      // 调用原始的 attached
      if (originalAttached) {
        originalAttached.call(this)
      }
    },
    
    detached() {
      // 取消订阅
      if (unsubscribe) {
        unsubscribe()
        unsubscribe = null
      }
      
      // 调用原始的 detached
      if (originalDetached) {
        originalDetached.call(this)
      }
    },
    
    methods: {
      ...componentConfig.methods,
      
      // 添加状态管理方法
      $getStore() {
        return appStore
      }
    }
  }
}

/**
 * 状态选择器
 * 用于从全局状态中选择特定的数据
 */
class StateSelector {
  /**
   * 选择用户信息
   */
  static selectUserInfo(state) {
    return state.userInfo
  }
  
  /**
   * 选择伴侣信息
   */
  static selectPartnerInfo(state) {
    return state.partnerInfo
  }
  
  /**
   * 选择当前心情
   */
  static selectCurrentEmotion(state) {
    return state.currentEmotion
  }
  
  /**
   * 选择情感天气
   */
  static selectEmotionWeather(state) {
    return state.emotionWeather
  }
  
  /**
   * 选择所有胶囊
   */
  static selectCapsules(state) {
    return state.capsules
  }
  
  /**
   * 选择未锁定的胶囊
   */
  static selectUnlockedCapsules(state) {
    return state.capsules.filter(capsule => !capsule.isLocked)
  }
  
  /**
   * 选择锁定的胶囊
   */
  static selectLockedCapsules(state) {
    return state.capsules.filter(capsule => capsule.isLocked)
  }
  
  /**
   * 选择特定类型的胶囊
   */
  static selectCapsulesByType(state, type) {
    return state.capsules.filter(capsule => capsule.type === type)
  }
  
  /**
   * 选择特定情感的胶囊
   */
  static selectCapsulesByEmotion(state, emotion) {
    return state.capsules.filter(capsule => capsule.emotion.emotion === emotion)
  }
  
  /**
   * 选择当前选中的胶囊
   */
  static selectSelectedCapsule(state) {
    return state.selectedCapsule
  }
  
  /**
   * 选择偷取历史
   */
  static selectStealHistory(state) {
    return state.stealHistory
  }
  
  /**
   * 选择应用状态
   */
  static selectAppStatus(state) {
    return {
      isLoading: state.isLoading,
      networkStatus: state.networkStatus,
      theme: state.theme
    }
  }
  
  /**
   * 选择是否已登录
   */
  static selectIsLoggedIn(state) {
    return state.userInfo.isLoggedIn
  }
  
  /**
   * 选择是否有伴侣
   */
  static selectHasPartner(state) {
    return state.partnerInfo !== null
  }
}

/**
 * 状态操作器
 * 提供常用的状态操作方法
 */
class StateActions {
  /**
   * 用户登录
   */
  static login(userInfo) {
    appStore.login(userInfo)
  }
  
  /**
   * 用户登出
   */
  static logout() {
    appStore.logout()
  }
  
  /**
   * 更新用户信息
   */
  static updateUserInfo(userInfo) {
    appStore.setUserInfo(userInfo)
  }
  
  /**
   * 设置伴侣信息
   */
  static setPartner(partnerInfo) {
    appStore.setPartnerInfo(partnerInfo)
  }
  
  /**
   * 更新心情
   */
  static updateEmotion(emotion) {
    appStore.updateEmotion(emotion)
  }
  
  /**
   * 更新情感天气
   */
  static updateWeather(weather) {
    appStore.updateEmotionWeather(weather)
  }
  
  /**
   * 创建胶囊
   */
  static createCapsule(capsule) {
    return appStore.addCapsule(capsule)
  }
  
  /**
   * 更新胶囊
   */
  static updateCapsule(id, updates) {
    appStore.updateCapsule(id, updates)
  }
  
  /**
   * 删除胶囊
   */
  static deleteCapsule(id) {
    appStore.deleteCapsule(id)
  }
  
  /**
   * 解锁胶囊
   */
  static unlockCapsule(id) {
    appStore.unlockCapsule(id)
  }
  
  /**
   * 选择胶囊
   */
  static selectCapsule(capsule) {
    appStore.selectCapsule(capsule)
  }
  
  /**
   * 设置加载状态
   */
  static setLoading(isLoading) {
    appStore.setLoading(isLoading)
  }
  
  /**
   * 添加偷取记录
   */
  static addStealRecord(record) {
    appStore.addStealRecord(record)
  }
  
  /**
   * 设置偷取目标
   */
  static setStealTarget(target) {
    appStore.setStealTarget(target)
  }
}

/**
 * 状态持久化工具
 */
class StatePersistence {
  /**
   * 导出状态数据
   */
  static exportState() {
    const state = appStore.getState()
    return JSON.stringify(state, null, 2)
  }
  
  /**
   * 导入状态数据
   */
  static importState(stateJson) {
    try {
      const state = JSON.parse(stateJson)
      // 这里可以添加状态验证逻辑
      appStore.clearAll()
      // 重新设置状态
      Object.keys(state).forEach(key => {
        if (key === 'userInfo') {
          appStore.setUserInfo(state[key])
        } else if (key === 'partnerInfo') {
          appStore.setPartnerInfo(state[key])
        }
        // 添加其他状态的导入逻辑
      })
      return true
    } catch (error) {
      console.error('Failed to import state:', error)
      return false
    }
  }
  
  /**
   * 备份状态到云端
   */
  static async backupToCloud() {
    try {
      const state = appStore.getState()
      // 这里可以调用云函数或API来备份状态
      console.log('Backing up state to cloud:', state)
      return true
    } catch (error) {
      console.error('Failed to backup state to cloud:', error)
      return false
    }
  }
  
  /**
   * 从云端恢复状态
   */
  static async restoreFromCloud() {
    try {
      // 这里可以调用云函数或API来恢复状态
      console.log('Restoring state from cloud')
      return true
    } catch (error) {
      console.error('Failed to restore state from cloud:', error)
      return false
    }
  }
}

// 导出默认的状态管理实例
module.exports = {
  createPageWithStore,
  createComponentWithStore,
  StateSelector,
  StateActions,
  StatePersistence,
  appStore
}